class BluetoothService {
    constructor() {
        // 使用小写的 UUID
        this.SERVICE_UUID = '0000ffe0-0000-1000-8000-00805f9b34fb'
        this.CONTROL_CHARACTERISTIC_UUID = '0000ffe1-0000-1000-8000-00805f9b34fb'
        this.NOTIFY_CHARACTERISTIC_UUID = '0000ffe2-0000-1000-8000-00805f9b34fb'

        this.device = null
        this.server = null
        this.service = null
        this.controlCharacteristic = null
        this.notifyCharacteristic = null
        this.notificationCallback = null
    }

    // 检查浏览器是否支持 Web Bluetooth
    checkAvailability() {
        if (!navigator.bluetooth) {
            throw new Error('此浏览器不支持 Web Bluetooth')
        }
    }

    // 连接设备
    async connect() {
        try {
            console.log('开始搜索蓝牙设备...')
            // 请求选择设备
            this.device = await navigator.bluetooth.requestDevice({
                // 使用过滤器方式
                filters: [
                    {
                        services: [this.SERVICE_UUID]  // 使用服务UUID过滤
                    }
                ],
                optionalServices: [
                    this.CONTROL_CHARACTERISTIC_UUID,
                    this.NOTIFY_CHARACTERISTIC_UUID
                ]
            })

            console.log('设备已选择:', {
                name: this.device.name,
                id: this.device.id
            })

            // 监听设备断开连接
            this.device.addEventListener('gattserverdisconnected', this.onDisconnected.bind(this))

            // 连接到设备
            console.log('正在连接到GATT服务器...')
            this.server = await this.device.gatt.connect()

            // 获取服务
            console.log('正在获取服务...')
            this.service = await this.server.getPrimaryService(this.SERVICE_UUID)

            // 获取特征值
            console.log('正在获取特征值...')
            this.controlCharacteristic = await this.service.getCharacteristic(this.CONTROL_CHARACTERISTIC_UUID)
            this.notifyCharacteristic = await this.service.getCharacteristic(this.NOTIFY_CHARACTERISTIC_UUID)

            // 启用通知
            console.log('正在启用通知...')
            await this.notifyCharacteristic.startNotifications()
            this.notifyCharacteristic.addEventListener('characteristicvaluechanged', this.onNotificationReceived.bind(this))

            console.log('蓝牙连接已完成')
            return true
        } catch (error) {
            console.error('连接失败:', error)
            throw error
        }
    }

    // 断开连接
    async disconnect() {
        if (this.device && this.device.gatt.connected) {
            await this.device.gatt.disconnect()
        }
    }

    // 设置通知回调
    setNotificationCallback(callback) {
        this.notificationCallback = callback
    }

    // 处理接收到的通知
    onNotificationReceived(event) {
        const value = event.target.value
        const decoder = new TextDecoder()
        const data = decoder.decode(value)

        if (this.notificationCallback) {
            this.notificationCallback(data)
        }
    }

    // 发送命令
    async sendCommand(command) {
        if (!this.controlCharacteristic) {
            throw new Error('未连接到设备')
        }

        const encoder = new TextEncoder()
        const data = encoder.encode(command)
        await this.controlCharacteristic.writeValue(data)
    }

    // 开始录制
    async startRecording() {
        await this.sendCommand('START_RECORDING')
    }

    // 停止录制
    async stopRecording() {
        await this.sendCommand('STOP_RECORDING')
    }

    // 处理设备断开连接
    onDisconnected() {
        console.log('设备已断开连接')
        this.device = null
        this.server = null
        this.service = null
        this.controlCharacteristic = null
        this.notifyCharacteristic = null
    }
}

// 导出单个实例
export default new BluetoothService()